package com.zsgl.test;

import junit.framework.TestCase;

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;

public class SpringControllerTestAdapter extends TestCase {

	protected MockHttpServletRequest request = new MockHttpServletRequest();
	
	protected MockHttpServletResponse response = new MockHttpServletResponse();
	
	protected HandlerAdapter handler = new AnnotationMethodHandlerAdapter(); 
	
	public ModelAndView handle(String uri, Object controller) throws Exception {
		request.setRequestURI(uri);
		return handler.handle(request, response, controller);
	}
	
	public void assertMappingAndView(String uri, Object controller) {
		assertMapping(uri, uri, controller);
	}
	
	public void assertMapping(String uri, Object controller) {
		try {
			handle(uri, controller);
		} catch (Exception e) {
			fail(uri + " has not been mapping!");
		}
	}
	
	public void assertMapping(String uri, String view, Object controller) {
		try {
			ModelAndView mav = handle(uri, controller);
			String viewName = mav.getViewName();
			if (viewName == null) {
				mav.setViewName(uri);
			}
			assertEquals(view, mav.getViewName());
		} catch (Exception e) {
			fail(uri + " has not been mapping or viewName not " + view);
		}
	}
	
	
	
}
